angular.module("config")
    .controller("commonController", function ($scope, $http,$rootScope, $location, $anchorScroll,md5) {
        $rootScope.imgPath = 'http://zha-ita112-w7:8080/';


        $scope.uname = null;

        var userlogin = false;
        var req = {
            method: "GET",
            url: "/client"
        };

        $http(req)
            .then(function (res) {
                console.log(res.data.error)
                if (!res.data.error) {
                    userlogin = true;
                    $scope.uname = res.data.cPersonName;
                }
            });

        $scope.isLogin = function () {
            return userlogin;
        };

        $scope.login = function () {
            var req = {
                method: "post",
                url: "/client/login",
                data: {
                    cTel: $scope.username,
                    cPassword: md5.createHash($scope.password || "")
                }
            }
            $http(req)
                .then(function (res) {
                    if (res.data.error) {
                        alert(res.data.error);
                    }
                    else {
                        $scope.username = null;
                        $scope.password = null;
                        $scope.uname = res.data.cPersonName;
                        $scope.$broadcast('UserLogin', res.data);
                        userlogin = true;
                    }
                })
        }

        $scope.logout = function () {
            var req = {
                method: "get",
                url: "/client/logout",
            }
            $http(req)
                .then(function (res) {
                    if (res.data.error) {
                        alert(res.data.error);
                    }
                    else {
                        $scope.cart;
                        userlogin = false;
                        $scope.$broadcast('UserLogout', "User logout");
                    }
                })
        }

        $scope.$on('UserRegist', function (event,data) {
            $scope.uname = data;
            userlogin = true;
        });

        $scope.gotoTop = function () {
            $location.hash('top');
            // call $anchorScroll()
            $anchorScroll();
        }


        $scope.$on('changeTopStyle', function(event, data) {
            $scope.b_uniform = data;
        });
    });
